<template>
  <van-swipe class="swiper"
    :autoplay="3000"
    :stop-propagation="false"
    indicator-color="#dd001b">
    <van-swipe-item class="swiper-item"
      v-for="(item, index) of banners" :key=index
      @click.stop="onClick(item)">
      <img v-lazy="item.pic"
        :src="item.pic"
        :alt="item.typeTitle">
      <span class="item-tag"
        :style="{ background: item.titleColor }">{{ item.typeTitle }}</span>
    </van-swipe-item>
  </van-swipe>
</template>

<script>
export default {
  name: 'home-swiper',
  data () {
    return {
      banners: []
    }
  },
  mounted () {
    this.initData()
  },
  methods: {
    initData () {
      this.$api.getBanner(1).then(res => {
        const { data } = res
        if (data.code === 200) {
          this.banners = data.banners.map(Object.freeze)
        }
      })
    },
    onClick (item) {
      if (item.url) {
        return window.open(item.url)
      }

      if (item.song) {
        return this.$store.dispatch('player/changeSong', { song: item.song })
      }

      if (item.encodeId) {
        return this.$router.push(`/album/${item.encodeId}`)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
/* 使用了两层 padding-bottom 为图片占位，并保证容器的高度 */
.swiper {
  overflow: hidden;
  width: 100%;
  height: 0;
  padding-bottom: 39%;
  &-item {
    overflow: hidden;
    width: 100%;
    height: 0;
    /* 这个 3.9% 有待理解 */
    padding-bottom: 3.9%;
    box-sizing: border-box;
    padding-left: .1rem;
    padding-right: .1rem;
    border-radius: .1rem;
    img {
      width: 100%;
      border-radius: .1rem;
    }
    .item-tag {
      position: absolute;
      right: .1rem;
      bottom: .08rem;
      padding: .03rem .06rem;
      color: #fff;
      font-size: 12px;
      background-color: #32d3ff;
      border-radius: .1rem 0 / .1rem 0;
    }
  }
}
</style>
